package com.example.she.lol;

import java.util.HashMap;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class MainActivity extends Activity {

    //可以被外部调用的MainActivity对象
    public static MainActivity CurActivity;

    MediaPlayer mMediaPlayer;

    private Handler handler;

    SoundPool soundPool;
    HashMap<Integer, Integer> soundPoolMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        InitSounds();
        setContentView(R.layout.activity_main);
        mMediaPlayer.setLooping(true);
        mMediaPlayer.start();
        CurActivity = this;
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg){
                super.handleMessage(msg);
                playSound(msg.arg1, 0);
            }
        };
    }

    ///发布一个公开的方法，可以在SurfaceView中跳转其他SurfaceView
    public void setView(){
        mMediaPlayer.stop();
        setContentView(R.layout.activity_game);
    }

    public Handler getHandler(){
        return this.handler;
    }

    @Override
    protected void onResume() {
        /**
         * 设置为横屏
         */
        if(getRequestedOrientation()!= ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        super.onResume();
    }

    private void InitSounds(){
        //背景音乐
        mMediaPlayer = MediaPlayer.create(this, R.raw.logchrsel);
        soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
        soundPoolMap = new HashMap<Integer, Integer>();
        soundPoolMap.put(1, soundPool.load(this, R.raw.step, 1));
        soundPoolMap.put(2, soundPool.load(this, R.raw.hj, 1));
    }

    public void playSound(int sound, int loop)
    {
        AudioManager mgr = (AudioManager) this
                .getSystemService(Context.AUDIO_SERVICE);
        float streamVolumeCurrent = mgr
                .getStreamVolume(AudioManager.STREAM_MUSIC);
        float streamVolumeMax = mgr
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        float volume = streamVolumeCurrent / streamVolumeMax;
        soundPool.play(soundPoolMap.get(sound), volume, volume, 1, loop, 1f);
    }

    @Override
    protected void onStop(){
        super.onStop();
        mMediaPlayer.stop();
    }
}